package com.yxhl.zoume.core.busticket.ui.fragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.services.core.PoiItem;
import com.yxhl.protobuf.BizOrder;
import com.yxhl.protobuf.BizOrderRequest;
import com.yxhl.protobuf.Contract;
import com.yxhl.protobuf.ContractType;
import com.yxhl.protobuf.GenderType;
import com.yxhl.protobuf.IdType;
import com.yxhl.protobuf.IsFerryRequest;
import com.yxhl.protobuf.OneBusEntry;
import com.yxhl.protobuf.OneYxBusInfoRequest;
import com.yxhl.protobuf.OneYxBusInfoResponse;
import com.yxhl.protobuf.OrderBizType;
import com.yxhl.protobuf.OrderSrcType;
import com.yxhl.protobuf.ScheduleType;
import com.yxhl.protobuf.StationEntry;
import com.yxhl.zoume.R;
import com.yxhl.zoume.common.presenter.PerfectCouponPresenter;
import com.yxhl.zoume.common.ui.fragment.BaseFragment;
import com.yxhl.zoume.common.ui.view.PerfectCouponView;
import com.yxhl.zoume.core.busticket.presenter.ZouMeBusOrderPresenter;
import com.yxhl.zoume.core.busticket.ui.activity.ZouMeBusOrderActivity;
import com.yxhl.zoume.core.busticket.view.ZouMeBusOrderView;
import com.yxhl.zoume.core.coupon.model.CouponSelectEvent;
import com.yxhl.zoume.core.coupon.model.CouponSelectModel;
import com.yxhl.zoume.core.func.map.ui.event.SelectUpPointEvent;
import com.yxhl.zoume.core.func.map.ui.event.SelectedPOIEvent;
import com.yxhl.zoume.core.func.passenger.event.DeletePsgerEvent;
import com.yxhl.zoume.core.func.passenger.event.RenderSelectedPsgersEvent;
import com.yxhl.zoume.core.func.passenger.ui.MultipleSelectType;
import com.yxhl.zoume.core.func.passenger.ui.PsgerItemType;
import com.yxhl.zoume.core.func.passenger.ui.SelectPsgersAdapter;
import com.yxhl.zoume.core.tripsmgmt.info.LocationMapEntrance;
import com.yxhl.zoume.core.tripsmgmt.info.ZouMeBusMapEntrance;
import com.yxhl.zoume.data.http.model.coupon.CouponInfo;
import com.yxhl.zoume.data.http.model.passenger.ZMPassenger;
import com.yxhl.zoume.di.component.busticket.BusServiceComponent;
import com.yxhl.zoume.di.component.coupon.DaggerPerfectCouponComponent;
import com.yxhl.zoume.di.module.ActivityModule;
import com.yxhl.zoume.domain.interactor.ZMEventSubscriber;
import com.yxhl.zoume.utils.DensityUtils;
import com.yxhl.zoume.utils.DiskCacheUtils;
import com.yxhl.zoume.utils.HTMLUtils;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.PromptUtils;
import com.yxhl.zoume.utils.ZMDialog;
import com.yxhl.zoume.utils.permission.PermissionHelper;
import com.yxhl.zoume.utils.timepicker.TimePickerHelper;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * 定制巴士-订单页面
 * <p>
 * Created by Xboy on 2016/05/21
 */
public class ZouMeBusOrderFragment extends BaseFragment implements ZouMeBusOrderView, PerfectCouponView {

    private static final String TAG = "ZouMeBusOrderFrag";

    private static final String KEY_ZOUMEBUS_DETAIL_PARAM = "KEY_ZOUMEBUS_DETAIL_PARAM";

    // 出发城市
    @BindView(R.id.start_city_textview)
    TextView mStartCityTextView;
    // 出发日期
    @BindView(R.id.zoume_bus_order_trip_date_textview)
    TextView mTripDateTextView;
    // 到达城市
    @BindView(R.id.arrival_city_textview)
    TextView mArrivalCityTextView;

    // 车型
    @BindView(R.id.bus_type_textview)
    TextView mBusTypeTextView;
    // 票价
    @BindView(R.id.bus_ticket_price_textview)
    TextView mBusTicketPriceTextView;

    // 出发地点
    @BindView(R.id.start_location_textview)
    TextView mStartLocationTextView;

    // 到站方式
    @BindView(R.id.radiogroup_arrival_approach)
    RadioGroup mArrivalApproachRadioGroup;
    @BindView(R.id.rb_by_shuttle)
    RadioButton mByShuttleRadioButton;
    @BindView(R.id.rb_by_self)
    RadioButton mBySelfRadioButton;

    // 乘车站点
    @BindView(R.id.include_zoume_bus_uppoint)
    RelativeLayout mUpPointLayout;
    // 请选择乘车站点
    @BindView(R.id.uppoint_textview)
    TextView mUpPointTextView;

    // 出行时间
    @BindView(R.id.trip_date_textview)
    TextView mTripTimeTextView;

    // 出行乘客列表
    @BindView(R.id.added_passengers_recycler)
    RecyclerView mAddedPassengersRecycler;

    // 总价:¥99.00
    @BindView(R.id.total_amount_textview)
    TextView mTotalAmountTextView;
    // 乘客人数:(5人)
    @BindView(R.id.passengers_number_textview)
    TextView mPsgersNumberTextView;
    // 确认按钮
    @BindView(R.id.order_confirm_textview)
    TextView mOrderConfirmTextView;

    //底栏箭头
    @BindView(R.id.iv_icon_up_arrow)
    ImageView mUpArrowIv;

    @BindView(R.id.rl_include_total_fee_container)
    RelativeLayout mTotalFeeContainerRl;

    //案底幕布
    @BindView(R.id.frame_zoume_bus_screen)
    FrameLayout mTicketScreenFrame;

    //底栏弹出窗
    @BindView(R.id.ll_zoume_bus_popup_container)
    LinearLayout mPopupContainerLl;
    //成人票
    @BindView(R.id.tv_zoume_bus_adult_price)
    TextView mAdultPriceTv;
    //儿童票
    @BindView(R.id.tv_zoume_bus_children_price)
    TextView mChildrenPriceTv;
    //接驳车票
    @BindView(R.id.tv_zoume_bus_shuttle_price)
    TextView mShuttlePriceTv;

    @BindView(R.id.tv_ticket_limit)
    TextView mTvTicketLimit;


    //优惠券
    @BindView(R.id.tv_bus_coupon_state)
    TextView mTvBusCouponState;
    @BindView(R.id.rl_bus_coupon_bar)
    RelativeLayout mRlBusCouponBar;
    @BindView(R.id.iv_bus_coupon_arrow)
    ImageView mIvBusCouponArrow;
    //弹出优惠券
    @BindView(R.id.tv_zoume_bus_pop_totle_coupon)
    TextView mTvZoumeBusPopTotleCoupon;

    // Injector
    BusServiceComponent component;

    // Recycler适配器
    SelectPsgersAdapter mSelectPsgersAdapter;

    @Inject
    ZouMeBusOrderPresenter orderPresenter;

    @Inject
    PerfectCouponPresenter mPerfectCouponPresenter;
    // 已添加的乘客
    List<ZMPassenger> selectedPsgers = new ArrayList<ZMPassenger>();
    // 成人数
    int adultCount = 0;
    // 儿童数
    int childCount = 0;
    // 订单总价
    double totalAmount;
    // Dialogs
    MaterialDialog dialogForWaitingDetail = null;
    MaterialDialog dialogForWaitingCheckIsNeedShuttle = null;
    MaterialDialog dialogForWaitingOrderConfirm = null;

    private CouponInfo perfectCoupon;
    // 详情数据请求体
    private OneYxBusInfoRequest mParam;
    // 出发地点
    private PoiItem startLocationInfo;
    // 乘车站点
    private StationEntry selectedUpPoint;
    // 当前车次
    private OneBusEntry currentBusService;
    // 票单价
    private double unitPrice;
    // 接驳车费用
    private String shuttlePrice;
    // 乘车站点
    private List<StationEntry> upPoints;
    // 接驳车
    private boolean isShuttleAvailable;
    /**
     * 旋转底栏箭头的起始角度
     */
    private int mFromDegree = 0;
    /**
     * 旋转底栏箭头的到达角度
     */
    private int mToDegree = 180;
    /**
     * 底栏箭头旋转和弹出框弹出标志位
     */
    private boolean needShowPopup = true;
    private String couponId;
    private int mTypeValue = 7;


    public static ZouMeBusOrderFragment newInstance(OneYxBusInfoRequest param) {
        Bundle args = new Bundle();
        args.putSerializable(KEY_ZOUMEBUS_DETAIL_PARAM, param);
        ZouMeBusOrderFragment fragment = new ZouMeBusOrderFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private void parseArguments() {
        Bundle args = getArguments();
        if (null != args) {
            mParam = (OneYxBusInfoRequest) args.getSerializable(KEY_ZOUMEBUS_DETAIL_PARAM);

        }
    }

    private void onRxBusEvent() {
        //选择出发地点
        getSubscription().add(toSubscription(SelectedPOIEvent.class,
                new Action1<SelectedPOIEvent>() {
                    @Override
                    public void call(SelectedPOIEvent selectedPOIEvent) {
                        startLocationInfo = selectedPOIEvent.getPoiItem();
                        mStartLocationTextView.setText(startLocationInfo.getTitle());

                        checkIsNeedShuttle(startLocationInfo);
                        checkOrderValidity();
                    }
                },
                new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LOG.e(TAG, "throwable=" + throwable.toString());
                        onRxBusEvent();
                    }
                }
        ));
        //选择乘车站点
        getSubscription().add(toSubscription(SelectUpPointEvent.class,
                new Action1<SelectUpPointEvent>() {
                    @Override
                    public void call(SelectUpPointEvent selectUpPointEvent) {
                        selectedUpPoint = selectUpPointEvent.getStationEntry();
                        mUpPointTextView.setText(selectedUpPoint.getStationName());

                        checkOrderValidity();
                    }
                },
                new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LOG.e(TAG, "throwable=" + throwable.toString());
                        onRxBusEvent();
                    }
                }
        ));

        getSubscription().add(toSubscription(RenderSelectedPsgersEvent.class,
                new Action1<RenderSelectedPsgersEvent>() {
                    @Override
                    public void call(RenderSelectedPsgersEvent renderSelectedPsgersEvent) {
                        selectedPsgers.clear();
                        selectedPsgers.addAll(renderSelectedPsgersEvent.getSelectedPsgers());
                        if (null == mSelectPsgersAdapter) {
                            refreshUI(selectedPsgers);
                        } else {
                            mSelectPsgersAdapter.notifyDataSetChanged();
                        }

                        // 计算乘客人数、订单总价
                        calculatePsgersNumber();
                        calculateTotalAmount();
                        queryPerfectCoupon();
                    }
                },
                new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LOG.e(TAG, "throwable=" + throwable.toString());
                        onRxBusEvent();
                    }
                }
        ));

        getSubscription().add(toSubscription(DeletePsgerEvent.class,
                new Action1<DeletePsgerEvent>() {
                    @Override
                    public void call(DeletePsgerEvent deletePsgerEvent) {
                        // 删除乘客
                        ZMPassenger p = deletePsgerEvent.getPassenger();
                        selectedPsgers.remove(p);

                        // 计算乘客人数、订单总价
                        calculatePsgersNumber();
                        calculateTotalAmount();
                        queryPerfectCoupon();
                    }
                }
        ));
        getSubscription().add(toSubscription(CouponSelectEvent.class, new Action1<CouponSelectEvent>() {
            @Override
            public void call(CouponSelectEvent couponSelectEvent) {
                couponId = couponSelectEvent.getCouponId();
                if (couponId != null) {
                    queryPerfectCoupon();
                } else {
                    //不使用优惠券
                    perfectCoupon = null;
                    notUseCoupon();
                }
            }
        }));
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 获取param
        parseArguments();
        onRxBusEvent();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 默认隐藏 "到站方式"
        mArrivalApproachRadioGroup.setVisibility(View.GONE);
        // 默认隐藏 "乘车站点"
        mUpPointLayout.setVisibility(View.GONE);
        mTvTicketLimit.setVisibility(View.INVISIBLE);

        // 配置recycler
        setupRecyclerView();

        // 获取车次详情
        orderPresenter.attachView(this);
        orderPresenter.getZouMeBusDetail(mParam);
        mPerfectCouponPresenter.attachView(this);
        mRlBusCouponBar.setClickable(false);

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        String isFirstRun = DiskCacheUtils.getInstance(mActivity).getZouMeBusDialogShowFlag();
        if ("true".equals(isFirstRun)) {
            DiskCacheUtils.getInstance(mActivity).putZouMeBusDialogShowFlag();

            ZMDialog dialog = new ZMDialog.Builder(component.context())
                    .setMessage(HTMLUtils.getRawContent(component.context(), R.raw.zou_me_bus_passenger_must_know_digest))
                    .setPositiveMessage("确定")
                    .setPositiveClickEvent(new ZMEventSubscriber() {
                        @Override
                        public void onNext(Object o) {
                            super.onNext(o);
                        }
                    }).show();
        }
    }

    /**
     * 检查是否需要接驳车
     *
     * @param poiItem
     */
    private void checkIsNeedShuttle(PoiItem poiItem) {
        if (isShuttleAvailable) {
            // TODO: 16/6/13 服务端改ScheduleId--No--long
            IsFerryRequest request = IsFerryRequest.newBuilder()
                    .setScheduleId(Long.valueOf(currentBusService.getScheduleNo()))
                    .setLng(String.valueOf(poiItem.getLatLonPoint().getLongitude()))
                    .setLat(String.valueOf(poiItem.getLatLonPoint().getLatitude()))
                    .setStartStationCode(currentBusService.getStartStationCode())
                    .setEndStationCode(currentBusService.getEndStationCode())
                    .build();
            orderPresenter.checkIsNeedShuttle(request);
        } else {
            //自定到站布局
            showUpPointLayout(false);
        }
    }

    /**
     * 计算订单总价
     */
    private void calculateTotalAmount() {
        // 儿童票半价

        totalAmount = unitPrice * 0.5 * childCount + unitPrice * adultCount;
        ;
        // ¥99.00
        mTotalAmountTextView.setText("¥" + String.format("%.2f", totalAmount));
    }

    /**
     * 计算乘客人数
     */
    private void calculatePsgersNumber() {
        // 总数
        int size = checkOrderValidity();
        // (5人)
        String psgersNumber = "(" + size + "人" + ")";
        mPsgersNumberTextView.setText(psgersNumber);

        // 成人、儿童
        adultCount = 0;
        childCount = 0;
        for (ZMPassenger p : selectedPsgers) {
            if (ZMPassenger.ADULT == p.getPsgerCategory()) {
                ++adultCount;
            } else {
                ++childCount;
            }
        }
    }

    /**
     * 检查订单能否确认下单
     *
     * @return
     */
    private int checkOrderValidity() {
        int size = selectedPsgers.size();
        boolean isNeedCheckTime = false;
        if (size > 0) {

            if(mArrivalApproachRadioGroup.getVisibility() ==View.VISIBLE) {

                if (mBySelfRadioButton.isChecked()) {
                    String upPointStation = mUpPointTextView.getText().toString();
                    if (!TextUtils.isEmpty(upPointStation)) {
                        isNeedCheckTime= true;
                    } else {
                        isNeedCheckTime = false;
                    }
                } else if (mByShuttleRadioButton.isChecked()) {
                    isNeedCheckTime= true;
                }
            }else{
                isNeedCheckTime=false;
            }
            mOrderConfirmTextView.setEnabled(isNeedCheckTime);

            if (isNeedCheckTime){

                if (TextUtils.isEmpty(mTripTimeTextView.getText().toString().trim())){
                    mOrderConfirmTextView.setEnabled(false);
                }else{
                    mOrderConfirmTextView.setEnabled(true);
                }

            }



        } else {
            mOrderConfirmTextView.setEnabled(false);
        }
        return size;
    }


//    /**
//     * 提交按钮师傅可用
//     */
//    public  void checkoutCommitEnable(){
//        if(mArrivalApproachRadioGroup.getVisibility() ==View.VISIBLE){
//
//            if (mBySelfRadioButton.isChecked()){
//                if (mUpPointTextView.getText().toString().trim().equals("")){
//                    mOrderConfirmTextView.setEnabled(false);
//                }else{
//                    mOrderConfirmTextView.setEnabled(true);
//                }
//            }else{
//                mOrderConfirmTextView.setEnabled(true);
//            }
//        }else{
//            mOrderConfirmTextView.setEnabled(false);
//        }
//
//        if (mTripTimeTextView.getText().toString().trim().equals("")){
//            mOrderConfirmTextView.setEnabled(false);
//        }else{
//            mOrderConfirmTextView.setEnabled(true);
//        }
//
//    }

    private void refreshUI(List<ZMPassenger> psgers) {
        mSelectPsgersAdapter = new SelectPsgersAdapter(component.context(), psgers, PsgerItemType.DELETABLE, ScheduleType.V_DIY_BUS);
        mAddedPassengersRecycler.setAdapter(mSelectPsgersAdapter);
    }


    /**
     * 配置RecyclerView
     */
    private void setupRecyclerView() {
        mAddedPassengersRecycler.setLayoutManager(new LinearLayoutManager(component.context()));
        mAddedPassengersRecycler.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    public void onResume() {
        super.onResume();
        orderPresenter.onResume();
        mPerfectCouponPresenter.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        orderPresenter.onPause();
        mPerfectCouponPresenter.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        orderPresenter.onDestroy();
        mPerfectCouponPresenter.onDestroy();
    }

    @Override
    protected void initializeInjector() {
        component = getComponent(BusServiceComponent.class);
        component.inject(this);

        DaggerPerfectCouponComponent
                .builder()
                .activityModule(new ActivityModule(mActivity))
                .appComponent(getAppComponent())
                .build()
                .inject(this);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_zoume_bus_order;
    }

    @Override
    protected void setupToolBar() {
        if (getActivity() instanceof ZouMeBusOrderActivity) {
            ((ZouMeBusOrderActivity) getActivity()).setToolbar(
                    getString(R.string.zoume_bus_title),
                    getString(R.string.zoume_bus_header_title));
        }
    }

    @Override
    public void waitingForZouMeBusDetailRequest(boolean isWaiting) {
        if (isWaiting) {
            dialogForWaitingDetail = new MaterialDialog.Builder(component.context())
                    .content(R.string.dialog_waiting_processing)
                    .progress(true, 0)
                    .canceledOnTouchOutside(false)
                    .show();
        } else {
            if (null != dialogForWaitingDetail) {
                dialogForWaitingDetail.dismiss();
            }
        }
    }

    @Override
    public void renderZouMeBusDetail(OneYxBusInfoResponse getZouMeBusDetailResponse) {
        // 定制巴士详情数据
        OneBusEntry busService = getZouMeBusDetailResponse.getOneBusInfo();
        currentBusService = busService;

        // 接驳车是否可用
        isShuttleAvailable = getZouMeBusDetailResponse.getFerry();
        // 出发城市
        mStartCityTextView.setText(busService.getStartStationName());
        // 出发日期
        mTripDateTextView.setText(busService.getGmtDepartDate());
        // 到达城市
        mArrivalCityTextView.setText(busService.getEndStationName());

        // 车型
        mBusTypeTextView.setText(getString(R.string.zoume_bus_model));
        // 票价
        mBusTicketPriceTextView.setText("¥" + busService.getTicketPrice());

        // 票单价
        unitPrice = Double.valueOf(busService.getTicketPrice());

        //接驳车价格
        shuttlePrice = getZouMeBusDetailResponse.getFerryPrice();

        // 乘车站点
        upPoints = getZouMeBusDetailResponse.getStationsList();
    }

    @Override
    public void waitingForCheckIsNeedShuttle(boolean isWaiting) {
        if (isWaiting) {
            dialogForWaitingCheckIsNeedShuttle = new MaterialDialog.Builder(component.context())
                    .content(R.string.dialog_waiting_processing)
                    .progress(true, 0)
                    .canceledOnTouchOutside(false)
                    .show();
        } else {
            if (null != dialogForWaitingCheckIsNeedShuttle) {
                dialogForWaitingCheckIsNeedShuttle.dismiss();
            }
        }
    }

    @Override
    public void renderCheckIsNeedShuttle(boolean isNeedShuttle) {
        if (isShuttleAvailable) {
            if (isNeedShuttle) {
                mArrivalApproachRadioGroup.setVisibility(View.VISIBLE);
                checkOrderValidity();
            } else {
                mArrivalApproachRadioGroup.setVisibility(View.GONE);
            }
            showUpPointLayout(isNeedShuttle);
        }
    }

    @Override
    public void showErrorMessage(String errorMessage) {
        new MaterialDialog.Builder(component.context())
                .title(R.string.dialog_title_hint)
                .content(errorMessage)
                .positiveText(R.string.dialog_confirm)
                .positiveColorRes(R.color.app_primary_blue)
                .canceledOnTouchOutside(false)
                .show();
    }

    @Override
    public void waitingForGenerateOrder(boolean isWaiting) {
        if (isWaiting) {
            dialogForWaitingOrderConfirm = new MaterialDialog.Builder(component.context())
                    .content(R.string.dialog_waiting_processing)
                    .progress(true, 0)
                    .canceledOnTouchOutside(false)
                    .show();
        } else {
            if (null != dialogForWaitingOrderConfirm) {
                dialogForWaitingOrderConfirm.dismiss();
            }
        }
    }

    @Override
    public void renderZouMeBusOrder(BizOrder order) {
        getAppComponent().navigator().navigateToPayment(component.context(), order);
    }

    /**
     * 选择出发地点
     */
    @OnClick(R.id.include_zoume_bus_location)
    void onLocationSelect() {
        boolean checkLocationPermission = PermissionHelper.checkLocationPermission(mActivity);
        if (checkLocationPermission) {
            getAppComponent().navigator().navigateToLocationMapActivity(mActivity, LocationMapEntrance.ZOUME_BUS_START);
        } else {
            PermissionHelper.takeLocationPermission(this, PermissionHelper.REQUEST_CODE_STATION_MAP_DEPART_LOCATION);
        }
    }

    /**
     * 选择到站方式
     */
    @OnClick({R.id.rb_by_shuttle, R.id.rb_by_self})
    void onArrivalApproachSelect() {
        showUpPointLayout(mByShuttleRadioButton.isChecked());
        checkOrderValidity();
    }

    /**
     * @param isShow true 表示接驳到站,不显示乘车站点栏;false 自行到站,显示乘车站点
     */
    private void showUpPointLayout(boolean isShow) {
        if (isShow) { //接驳到站
            mUpPointLayout.setVisibility(View.GONE);
        } else { //自行到站
            mUpPointLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 选择乘车站点
     */
    @OnClick(R.id.include_zoume_bus_uppoint)
    void onUpPointSelect() {

        getAppComponent().navigator().navigateToZouMeBusMapContainerActivity(getActivity(), upPoints, ZouMeBusMapEntrance.ZOUME_BUS_ORDER);
    }

    /**
     * 选择出行时间
     */
    @OnClick(R.id.include_trip_date_layout)
    void onTripDateSelect() {

        TimePickerHelper.newInstance(component.context())
                .showZouMeBusTimePicker(currentBusService.getGmtDepartDate(), new TimePickerHelper.OnTimeOptionSelectListener() {
                    @Override
                    public void onTimeOptionSelect(String timeSelected) {
                        mTripTimeTextView.setText(timeSelected.trim());
                        checkOrderValidity();
                    }
                });
    }

    /**
     * 选择出行乘客
     */
    @OnClick(R.id.include_add_passenger_operation_bar)
    void onPassengersSelect() {
        getAppComponent().navigator().navigateToSelectPassengers(
                component.context(),
                selectedPsgers,
                PsgerItemType.MULTI_SELECT,
                MultipleSelectType.ZOU_ME_BUS_ORDER_MULTI_SELECT
        );
    }

    /**
     * 确认订单
     */
    @OnClick(R.id.order_confirm_textview)
    void onOrderConfirmClick() {

        // 接驳车
        boolean isNeedShuttle = mArrivalApproachRadioGroup.getVisibility() == View.VISIBLE & mByShuttleRadioButton.isChecked();
        // 出发地点 or 乘车站点
//        String startLoc = "";
//        if(isNeedShuttle){
//            startLoc = mStartLocationTextView.getText().toString();
//        }else{
//            if(selectedUpPoint != null){
//                startLoc = String.valueOf(selectedUpPoint.getId());
//            }
//        }
        String startLoc = isNeedShuttle ? mStartLocationTextView.getText().toString() : String.valueOf(selectedUpPoint.getId());
        // 出行乘客
        List<Contract> allPsgers = new ArrayList<>();
        for (ZMPassenger p : selectedPsgers) {
            Contract c = Contract.newBuilder()
                    .setContractType(p.getPsgerCategory() == ZMPassenger.ADULT ? ContractType.ADULT : ContractType.CHILDREN)
                    .setId(Long.valueOf(p.getPassengerId()))
                    .setIdType(p.getIdType() == 0 ? IdType.IT_DEFAULT : IdType.IDCARD)
                    .setIdNumber(p.getIdNumber())
                    .setRealname(p.getRealName())
                    .setMobile(p.getMobileNumber())
                    .setGender(p.getGender() == 0 ? GenderType.GT_DEFAULT : (p.getGender() == 1 ? GenderType.MALE : GenderType.FEMALE))
                    .build();
            allPsgers.add(c);
        }

        long userCouponId = 0;
        double discountFee = 0;
        double orderTotalFee = totalAmount;
        if (null != perfectCoupon) {
            userCouponId = perfectCoupon.getUserCouponId();
            discountFee = perfectCoupon.getDiscountFee();
            orderTotalFee = perfectCoupon.getTotalFee();
        }

        BizOrderRequest.Builder rb = BizOrderRequest.newBuilder()
                .setSrc(OrderSrcType.APP)
                .setBizType(OrderBizType.OBT_DIY_BUS)
                .setScheduleId(Long.valueOf(currentBusService.getScheduleNo()))
                .setTotalFee(orderTotalFee)
                .setDepartTime(currentBusService.getGmtDepartDate() + " " + mTripTimeTextView.getText().toString())
                .setStartStation(currentBusService.getStartStationCode())
                .setEndStation(currentBusService.getEndStationCode())
                .setNeedFerry(isNeedShuttle)
                .setLat(String.valueOf(startLocationInfo.getLatLonPoint().getLatitude()))
                .setLng(String.valueOf(startLocationInfo.getLatLonPoint().getLongitude()))
                .setStart(startLoc)
                .addAllContracts(allPsgers)
                .setCouponUserRelId(userCouponId)
                .setDiscountFee(discountFee);

        // 确认订单
        orderPresenter.generateOrder(rb);
    }


    @OnClick(R.id.frame_zoume_bus_screen)
    public void onPopupOutsideScreenClick(View view) {
        if (!needShowPopup) {
            startArrowRotationAnimator();
        }
    }

    /**
     * 查看价格详情
     *
     * @param view
     */
    @OnClick(R.id.rl_include_total_fee_container)
    public void onTotalFeeContainerClick(View view) {
        bindBottomPopupData(selectedPsgers);
        startArrowRotationAnimator();
    }

    /**
     * 填充弹出框数据
     */
    private void bindBottomPopupData(List<ZMPassenger> zmPassengerList) {
        mAdultPriceTv.setText(String.format("%.2f", unitPrice) + "元 X" + adultCount);
        mChildrenPriceTv.setText(String.format("%.2f", unitPrice * 0.5f) + "元 X" + childCount);
        mShuttlePriceTv.setText(shuttlePrice + "元");
    }

    /**
     * 选择优惠券
     */
    @OnClick(R.id.rl_bus_coupon_bar)
    public void onSelectCouponClick() {
        CouponSelectModel couponSelectModel = new CouponSelectModel();
        couponSelectModel.setBizType(mTypeValue)
                .setOrderTotalFee(String.valueOf(totalAmount))
                .setCouponUserRelId(couponId);
        getAppComponent().navigator().navigateToCouponSelectPage(mActivity, couponSelectModel);
    }

    /**
     * 开启箭头旋转动画
     */
    private void startArrowRotationAnimator() {
        ValueAnimator passengerArrowAnimator = ObjectAnimator.ofFloat(mUpArrowIv, "rotation", mFromDegree, mToDegree);
        passengerArrowAnimator.setDuration(300);
        passengerArrowAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                if (needShowPopup) {
                    mFromDegree = 180;
                    mToDegree = 360;
                } else {
                    mFromDegree = 0;
                    mToDegree = 180;
                }
                startPopupAnimator(needShowPopup);
                needShowPopup = !needShowPopup;
            }
        });
        passengerArrowAnimator.start();
    }

    /**
     * 启动/退出底栏弹出框
     *
     * @param needUpTranslation true,需要向上弹出,false,需要向下退出弹框
     */
    private void startPopupAnimator(boolean needUpTranslation) {
        float height = DensityUtils.dip2px(mActivity, 149);

        PropertyValuesHolder translationValuesHolder;
        PropertyValuesHolder alphaValuesHolder;
        ObjectAnimator translationAnimator;
        //上移
        if (needUpTranslation) {
            translationValuesHolder = PropertyValuesHolder.ofFloat("translationY", 0, (-1) * height);
            alphaValuesHolder = PropertyValuesHolder.ofFloat("alpha", 0f, 1f);
            translationAnimator = ObjectAnimator.ofPropertyValuesHolder(
                    mPopupContainerLl,
                    translationValuesHolder,
                    alphaValuesHolder
            );
            translationAnimator.setInterpolator(new DecelerateInterpolator());
            mTicketScreenFrame.setVisibility(View.VISIBLE);
        }
        //下移
        else {
            translationValuesHolder = PropertyValuesHolder.ofFloat("translationY", (-1) * height, 0);
            alphaValuesHolder = PropertyValuesHolder.ofFloat("alpha", 1f, 0f);
            translationAnimator =
                    ObjectAnimator.ofPropertyValuesHolder(
                            mPopupContainerLl,
                            translationValuesHolder,
                            alphaValuesHolder
                    );
            translationAnimator.setInterpolator(new AccelerateInterpolator());
            mTicketScreenFrame.setVisibility(View.GONE);
        }

        translationAnimator.setDuration(300);
        translationAnimator.start();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            //快车出发站点
            case PermissionHelper.REQUEST_CODE_STATION_MAP_DEPART_LOCATION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    getAppComponent().navigator().navigateToLocationMapActivity(mActivity, LocationMapEntrance.ZOUME_BUS_START);
                } else {
                    PromptUtils.showShort(mActivity, getString(R.string.permission_location_deny_message));
                }
                break;
        }
    }

    /**
     * 查询最佳
     */
    private void queryPerfectCoupon() {
        if (selectedPsgers.size() == 0) {
            mRlBusCouponBar.setClickable(false);
            mIvBusCouponArrow.setVisibility(View.INVISIBLE);
            return;
        }
        showWaitingDialog(true);

        mPerfectCouponPresenter.queryPerfectCoupon(mTypeValue, totalAmount, couponId);
    }

    /**
     * 不使用优惠券
     */
    public void notUseCoupon() {
        mIvBusCouponArrow.setVisibility(View.VISIBLE);
        mTvBusCouponState.setSelected(false);
        mTvBusCouponState.setText("不使用优惠券");
        mTvZoumeBusPopTotleCoupon.setText("不使用优惠券");
        mTotalAmountTextView.setText("¥" + String.format("%.2f", totalAmount));

    }

    @Override
    public void renderPerfectCouponSuccess(CouponInfo perfectCoupon) {
        showWaitingDialog(false);
        String content = "";
        if (null != perfectCoupon.getCouponName()) {
            this.perfectCoupon = perfectCoupon;
            mTvBusCouponState.setSelected(true);
            content = perfectCoupon.getCouponName() + "   -¥" + (perfectCoupon.getDiscountFee());
            mTvBusCouponState.setText(content);
            mTvZoumeBusPopTotleCoupon.setText("-¥" + perfectCoupon.getDiscountFee());
            mTotalAmountTextView.setText("¥" + String.format("%.2f", perfectCoupon.getTotalFee()));
            couponId = String.valueOf(perfectCoupon.getUserCouponId());
            mRlBusCouponBar.setClickable(true);
            mIvBusCouponArrow.setVisibility(View.VISIBLE);
        } else {
            mRlBusCouponBar.setClickable(false);
            mIvBusCouponArrow.setVisibility(View.INVISIBLE);
        }

    }

    @Override
    public void renderPerfectCouponFailure() {
        showWaitingDialog(false);
    }

    public void showWaitingDialog(boolean isWaiting) {
        if (isWaiting) {
            dialogForWaitingDetail = new MaterialDialog.Builder(component.context())
                    .content(R.string.dialog_waiting_processing)
                    .progress(true, 0)
                    .canceledOnTouchOutside(false)
                    .show();
        } else {
            if (null != dialogForWaitingDetail) {
                dialogForWaitingDetail.dismiss();
            }
        }
    }
}
